﻿
var DbService = function () {
    this.initialized = false;
};

DbService.prototype.init = function (callback) {
    if (!this.initialized) {
        this.initialized = true;
        var db = new BloggerDbContext();
        try {
            db.init(callback);
        }
        catch (ex) {
            alert(ex);
        }
    }
    else {
        callback();
    }
};

DbService.prototype.getWebServiceUrl = function (callback) {
    new BloggerDbContext().settings.where("key='" + Setting.keys.WebServiceUrl+ "'").toArray(function (items) {
        callback(items.firstOrDefault().value);
    });
};

DbService.prototype.getInterval = function (callback) {
    new BloggerDbContext().settings.where("key='" + Setting.keys.AutoSaveIntervalSeconds + "'").toArray(function(items) {
        callback(items.firstOrDefault().value);
    });
};

DbService.prototype.updateSettings = function(settings, callback) {
    var db = new BloggerDbContext();
    db.settings.toArray(function(dbSettings) {
        for (var i = 0; i < dbSettings.length; i++) {
            var dbSetting = dbSettings[i];
            for (var j = 0; j < settings.length; j++) {
                var setting = settings[j];
                if (setting.key = dbSetting.key) {
                    dbSetting.value = setting.value;
                }
            }
            db.settings.update(dbSetting);
        }
        db.saveChanges(callback);
    });
};

DbService.prototype.getBlogs = function (callback) {
    new BloggerDbContext().blogs.toArray(function (items) {
        callback(items);
    });
};

DbService.prototype.getBlog = function(id, callback) {
    new BloggerDbContext().blogs.where("id=" + id).toArray(function(items) {
        callback(items.firstOrDefault());
    });
};

DbService.prototype.saveBlog = function(blog, callback) {
    var obj = this;
    var db = new BloggerDbContext();
    if (blog.id > 0) {
        obj.getBlog(blog.id, function(dbBlog) {
            dbBlog.update(blog);
            db.blogs.update(dbBlog);
            db.saveChanges(callback);
        });
    } else {
        db.blogs.add(blog);
        db.saveChanges(callback);
    }
};

DbService.prototype.deleteBlog = function (id, callback) {
    var db = new BloggerDbContext();
    this.getBlog(id, function (blog) {
        db.blogs.remove(blog);
        db.saveChanges(callback);
    });
};